package xhwl.hmo.mall.ui.fragment;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;

import java.util.ArrayList;

import de.greenrobot.event.EventBus;
import xhwl.hmo.mall.R;
import xhwl.hmo.mall.adapter.MineAdressAdapter;
import xhwl.hmo.mall.event.LoginEvent;
import xhwl.hmo.mall.event.UpdateUserInfoEvent;
import xhwl.hmo.mall.http.api.AddressListApi;
import xhwl.hmo.mall.http.api.GuaranteeApi;
import xhwl.hmo.mall.http.api.OrderNumApi;
import xhwl.hmo.mall.http.api.UserInfoApi;
import xhwl.hmo.mall.http.bean.resp.AddressListResp;
import xhwl.hmo.mall.http.bean.resp.HttpResp;
import xhwl.hmo.mall.http.bean.resp.MineAdressBean;
import xhwl.hmo.mall.http.bean.resp.OrderNumBean;
import xhwl.hmo.mall.http.bean.resp.UserInfoResp;
import xhwl.hmo.mall.ui.AddressManageActivity;
import xhwl.hmo.mall.ui.MessageActivity;
import xhwl.hmo.mall.ui.MyOrderListActivity;
import xhwl.hmo.mall.ui.PersonListActivity;
import xhwl.hmo.mall.ui.SettingsActivity;
import xhwl.hmo.mall.utils.AppUtil;
import xhwl.hmo.mall.utils.GlideCircleTransform;
import xhwl.hmo.mall.utils.SpUtil;
import xhwl.hmo.mall.utils.StringUtil;
import xhwl.retrofitrx.HttpManager;
import xhwl.retrofitrx.OnNextListener;


/**
 * Created by admin on 2017-10-20.
 */

public class MineFragment extends BaseFragment implements View.OnClickListener {
    private ImageView settings;
    private ImageView message;
    private ImageView img_header;
    private TextView name;
    private TextView phone;
    private RelativeLayout order_layout;
    private LinearLayout pay_waiting;
    private TextView dot_pay_waiting;
    private LinearLayout delivery_good_waiting;
    private TextView dot_delivery_good_waiting;
    private LinearLayout take_delivery_good_waiting;
    private TextView dot_take_delivery_good_waiting;
    private LinearLayout comment_waiting;
    private TextView dot_comment_waiting;
    private RelativeLayout info_baozhangren_layout;
    private RelativeLayout servicephone_layout;
    private RelativeLayout addressrecord_layout;
    Button btnLogin;
    TextView num_record, person_count;

    private MineAdressAdapter adapter;
    ArrayList<MineAdressBean.PersonInfoBean> mlist = new ArrayList<>();
    private RecyclerView mRecyclerView;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_mine, null);
        return view;
    }

    @Override
    protected void initView(View view) {
        btnLogin = (Button) view.findViewById(R.id.btnLogin);
        settings = (ImageView) view.findViewById(R.id.settings);
        message = (ImageView) view.findViewById(R.id.message);
        img_header = (ImageView) view.findViewById(R.id.img_header);
        name = (TextView) view.findViewById(R.id.name);
        phone = (TextView) view.findViewById(R.id.phone);
        order_layout = (RelativeLayout) view.findViewById(R.id.order_layout);
        pay_waiting = (LinearLayout) view.findViewById(R.id.pay_waiting);
        dot_pay_waiting = (TextView) view.findViewById(R.id.dot_pay_waiting);
        delivery_good_waiting = (LinearLayout) view.findViewById(R.id.delivery_good_waiting);
        dot_delivery_good_waiting = (TextView) view.findViewById(R.id.dot_delivery_good_waiting);
        take_delivery_good_waiting = (LinearLayout) view.findViewById(R.id.take_delivery_good_waiting);
        dot_take_delivery_good_waiting = (TextView) view.findViewById(R.id.dot_take_delivery_good_waiting);
        comment_waiting = (LinearLayout) view.findViewById(R.id.comment_waiting);
        dot_comment_waiting = (TextView) view.findViewById(R.id.dot_comment_waiting);
        info_baozhangren_layout = (RelativeLayout) view.findViewById(R.id.info_baozhangren_layout);
        mRecyclerView = (RecyclerView) view.findViewById(R.id.recyclerView);
        servicephone_layout = (RelativeLayout) view.findViewById(R.id.servicephone_layout);
        addressrecord_layout = (RelativeLayout) view.findViewById(R.id.addressrecord_layout);
        num_record = (TextView) view.findViewById(R.id.num_record);
        person_count = (TextView) view.findViewById(R.id.person_count);
    }

    @Override
    protected void initListener() {
        btnLogin.setOnClickListener(this);
        settings.setOnClickListener(this);
        message.setOnClickListener(this);
        img_header.setOnClickListener(this);
        order_layout.setOnClickListener(this);
        pay_waiting.setOnClickListener(this);
        delivery_good_waiting.setOnClickListener(this);
        take_delivery_good_waiting.setOnClickListener(this);
        comment_waiting.setOnClickListener(this);
        info_baozhangren_layout.setOnClickListener(this);
        servicephone_layout.setOnClickListener(this);
        addressrecord_layout.setOnClickListener(this);
    }

    @Override
    protected void loadData() {

        if (AppUtil.isLogin()) {
            settings.setVisibility(View.VISIBLE);
            message.setVisibility(View.VISIBLE);
            name.setVisibility(View.VISIBLE);
            phone.setVisibility(View.VISIBLE);

            btnLogin.setVisibility(View.GONE);
            addressrecord_layout.setVisibility(View.VISIBLE);
            getUserInfo();
            getAddrList(1);
            getOrderNum();
            getGuaranteeList();
        } else {
            settings.setVisibility(View.INVISIBLE);
            message.setVisibility(View.INVISIBLE);
            name.setVisibility(View.GONE);
            phone.setVisibility(View.GONE);

            btnLogin.setVisibility(View.VISIBLE);
            addressrecord_layout.setVisibility(View.GONE);

            person_count.setText("");
            name.setText("未登录");
            phone.setText("");
            Glide.with(getActivity()).load(SpUtil.getString(SpUtil.MEMBER_HEAD, ""))
                    .transform(new GlideCircleTransform(getActivity()))
                    .error(R.drawable.head)
                    .into(img_header);
            mlist.clear();
            adapter.notifyDataSetChanged();
            dot_pay_waiting.setVisibility(View.GONE);
            dot_comment_waiting.setVisibility(View.GONE);
            dot_delivery_good_waiting.setVisibility(View.GONE);
            dot_take_delivery_good_waiting.setVisibility(View.GONE);
        }
    }

    @Override
    protected void processOper() {
        super.processOper();
        initRecylerView();
        adapter = new MineAdressAdapter(getActivity(), mlist);
        mRecyclerView.setAdapter(adapter);
    }

    @Override
    public void onResume() {
        super.onResume();
        if (AppUtil.isLogin()) {
            //返回时刷新小红点
            getOrderNum();
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btnLogin:
                if (!AppUtil.isLogin()) {
                    AppUtil.startLoginActivity(mActivity);
                    return;
                }
                break;
            case R.id.settings: {
                Intent intent = new Intent(mActivity, SettingsActivity.class);
                startActivity(intent);
            }
            break;
            case R.id.message:
                startActivity(new Intent(getActivity(), MessageActivity.class));
                break;
            case R.id.img_header:

                break;
            case R.id.order_layout:
                if (!AppUtil.isLogin()) {
                    AppUtil.startLoginActivity(mActivity);
                    return;
                }
                startActivity(new Intent(getActivity(), MyOrderListActivity.class));
                break;
            case R.id.pay_waiting:
                if (!AppUtil.isLogin()) {
                    AppUtil.startLoginActivity(mActivity);
                    return;
                }
                Intent intentpay_waiting = new Intent(getActivity(), MyOrderListActivity.class);
                intentpay_waiting.putExtra(MyOrderListActivity.EXTRA_TAB_INDEX, 1);
                getActivity().startActivity(intentpay_waiting);
                break;
            case R.id.delivery_good_waiting:
                if (!AppUtil.isLogin()) {
                    AppUtil.startLoginActivity(mActivity);
                    return;
                }
                Intent intents = new Intent(getActivity(), MyOrderListActivity.class);
                intents.putExtra(MyOrderListActivity.EXTRA_TAB_INDEX, 2);
                getActivity().startActivity(intents);
                break;
            case R.id.comment_waiting:
                if (!AppUtil.isLogin()) {
                    AppUtil.startLoginActivity(mActivity);
                    return;
                }
                Intent intentss = new Intent(getActivity(), MyOrderListActivity.class);
                intentss.putExtra(MyOrderListActivity.EXTRA_TAB_INDEX, 4);
                getActivity().startActivity(intentss);
                break;
            case R.id.take_delivery_good_waiting:
                if (!AppUtil.isLogin()) {
                    AppUtil.startLoginActivity(mActivity);
                    return;
                }
                Intent inten = new Intent(getActivity(), MyOrderListActivity.class);
                inten.putExtra(MyOrderListActivity.EXTRA_TAB_INDEX, 3);
                getActivity().startActivity(inten);
                break;
            case R.id.servicephone_layout:
                if (ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.CALL_PHONE)
                        != PackageManager.PERMISSION_GRANTED) {
                    requestPermissions(new String[]{Manifest.permission.CALL_PHONE}, 0);
                } else {
                    Uri data = Uri.parse("tel:" + "4006562020");
                    Intent intent = new Intent(Intent.ACTION_DIAL, data);
                    getActivity().startActivity(intent);
                }

                break;
            case R.id.addressrecord_layout:
                if (!AppUtil.isLogin()) {
                    AppUtil.startLoginActivity(mActivity);
                    return;
                }
            {
                Intent intent = new Intent(mActivity, AddressManageActivity.class);
                intent.putExtra(AddressManageActivity.EXTRA_SHOW_CONFIRM_DIALOG, false);
                startActivity(intent);
            }

            break;
            case R.id.info_baozhangren_layout:
                if (!AppUtil.isLogin()) {
                    AppUtil.startLoginActivity(mActivity);
                    return;
                }
            {
                Intent intent = new Intent(mActivity, PersonListActivity.class);
                startActivity(intent);
            }
            break;
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case 0:
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    Uri data = Uri.parse("tel:" + "4006562020");
                    Intent intent = new Intent(Intent.ACTION_DIAL, data);
                    getActivity().startActivity(intent);
                }
                break;
        }
    }

    private void getUserInfo() {
        UserInfoApi api = new UserInfoApi();
        HttpManager.getInstance().dealHttp(this, api, new OnNextListener<HttpResp<UserInfoResp>>() {
            @Override
            public void onNext(HttpResp<UserInfoResp> resp) {
                if (null != resp.data) {
                    if (!StringUtil.isEmpty(resp.data.getMember_name())) {
                        SpUtil.putString(SpUtil.MEMBER_NAME, resp.data.getMember_name());
                    }
                    if (!StringUtil.isEmpty(resp.data.getMember_pic())) {
                        SpUtil.putString(SpUtil.MEMBER_HEAD, resp.data.getMember_pic());
                    }
                    name.setText(resp.data.getMember_name());
                    phone.setText(resp.data.getMember_mobile());
                    if (resp.data.getMember_pic() != null) {
                        SpUtil.putString(SpUtil.MEMBER_HEAD, resp.data.getMember_pic());
                    }
                    Glide.with(getActivity()).load(resp.data.getMember_pic())
                            .transform(new GlideCircleTransform(getActivity()))
                            .error(R.drawable.head)
                            .into(img_header);
                }
            }
        });
    }

    private void getOrderNum() {
        OrderNumApi api = new OrderNumApi();
        HttpManager.getInstance().dealHttp(this, api, new OnNextListener<HttpResp<OrderNumBean>>() {
            @Override
            public void onNext(HttpResp<OrderNumBean> resp) {
                if (null != resp.data) {
                    if (!"0".equals(resp.data.getWait_pay())) {
                        dot_pay_waiting.setVisibility(View.VISIBLE);
//                        dot_pay_waiting.setText(resp.data.getWait_pay());
                    }else{
                        dot_pay_waiting.setVisibility(View.GONE);
                    }
                    if (!"0".equals(resp.data.getWait_send())) {
                        dot_delivery_good_waiting.setVisibility(View.VISIBLE);
//                        dot_delivery_good_waiting.setText(resp.data.getWait_send());
                    }else{
                        dot_delivery_good_waiting.setVisibility(View.GONE);
                    }
                    if (!"0".equals(resp.data.getTake_goods())) {
                        dot_take_delivery_good_waiting.setVisibility(View.VISIBLE);
//                        dot_take_delivery_good_waiting.setText(resp.data.getTake_goods());
                    }else{
                        dot_take_delivery_good_waiting.setVisibility(View.GONE);
                    }
                    if (!"0".equals(resp.data.getWait_comment())) {
                        dot_comment_waiting.setVisibility(View.VISIBLE);
//                        dot_comment_waiting.setText(resp.data.getWait_comment());
                    }else{
                        dot_comment_waiting.setVisibility(View.GONE);
                    }
                }
            }
        });
    }

    private void getAddrList(final int page) {
        String mobile = SpUtil.getString(SpUtil.MEMBER_MOBILE, "");
        if (StringUtil.isEmpty(mobile)) {
            return;
        }
        AddressListApi api = new AddressListApi(mobile, page);
        HttpManager.getInstance().dealHttp(this, api, new OnNextListener<HttpResp<AddressListResp>>() {
            @Override
            public void onNext(HttpResp<AddressListResp> resp) {
                if (resp != null) {
                    num_record.setText("共有" + resp.data.ADDRESS_NUM + "条地址记录");
                }
            }

        });
    }

    private void getGuaranteeList() {
        GuaranteeApi api = new GuaranteeApi();
        HttpManager.getInstance().dealHttp(this, api, new OnNextListener<HttpResp<MineAdressBean>>() {
            @Override
            public void onNext(HttpResp<MineAdressBean> resp) {
                if (null != resp.data) {
                    mlist.clear();
                    person_count.setText("您共有" + resp.data.getPerson_num() + "位保障人");
                    if (3 < resp.data.getPerson_info().size()) {
                        mlist.add(resp.data.getPerson_info().get(0));
                        mlist.add(resp.data.getPerson_info().get(1));
                        mlist.add(resp.data.getPerson_info().get(2));
                    } else {
                        mlist.addAll(resp.data.getPerson_info());
                    }
                    adapter.notifyDataSetChanged();
                }
            }
        });
    }

    public void onEvent(LoginEvent event) {
        if (event != null) {
            loadData();
        }
    }

    public void onEvent(UpdateUserInfoEvent event) {
        if (event != null) {
            Glide.with(getActivity()).load(SpUtil.getString(SpUtil.MEMBER_HEAD, ""))
                    .transform(new GlideCircleTransform(getActivity()))
                    .error(R.drawable.head)
                    .into(img_header);
            name.setText(SpUtil.getString(SpUtil.MEMBER_NAME, ""));
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    //设置recyclerview
    private void initRecylerView() {
        final LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        mRecyclerView.setLayoutManager(layoutManager);
        mRecyclerView.setHasFixedSize(true);
        mRecyclerView.setNestedScrollingEnabled(false);
        mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(RecyclerView mRecyclerView, int dx, int dy) {
                super.onScrolled(mRecyclerView, dx, dy);
            }
        });
    }

}
